//
//  DPMainViewController.m
//  DrinkingPlan
//
//  Created by 张德广 on 2019/3/15.
//  Copyright © 2019 Drinking Plan. All rights reserved.
//

#import "DPMainViewController.h"
#import "UIView+Shape.h"
#import <CoreLocation/CoreLocation.h>
#import "DPPlanViewController.h"
#import "DCHomeTableViewCell.h"
#import "DPPopView.h"
#import <AVFoundation/AVFoundation.h>
#import "DPProgressView.h"
#import "DPModel.h"
#import "WHWeatherView.h"
#import "WHWeatherHeader.h"
#import "ZFChart.h"

@interface DPMainViewController () <CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource,DCAlertViewDelegate,ZFGenericChartDataSource,ZFBarChartDelegate> {
    
    float _horizontal;
    float _horizontal2;
    float waterHeight;
}

@property (nonatomic, strong) UISegmentedControl *segmentedControl;

@property (nonatomic, strong) UIButton *todayBtn; // 今天的喝水计划
@property (nonatomic, strong) UIButton *dataBtn; // 本周喝水数据
@property (nonatomic, strong) UILabel *lineLabel; // 下移动线


// today's view
@property (nonatomic, strong) WHWeatherView *topView;

@property (nonatomic, strong) UIView *rippleOne;
@property (nonatomic, strong) UIView *rippleTwo;
@property (nonatomic, strong) UILabel *percentLabel;

@property (nonatomic, strong) NSTimer *waterTimer;
@property (nonatomic, strong) NSTimer *waterTimer2;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSString *city_code;

@property (nonatomic, strong) UILabel *temperatureLabel; // 温度
@property (nonatomic, strong) UIImageView *temperatureImg; // 天气图标
@property (nonatomic, strong) UILabel *timeLabel; // 时间

@property (nonatomic, strong) UILabel *todayPlanLabel;
@property (nonatomic, strong) UILabel *todayPlanNum;
@property (nonatomic, strong) UIButton *recommendBtn; // 我的计划

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *planDataArr;

// data's view
@property (nonatomic, strong) UIView *anotherTopView;
@property (nonatomic, strong) UILabel *weekWaterLabel;
@property (nonatomic, strong) UILabel *weekWaterNum;
@property (nonatomic, strong) UILabel *planWaterLabel;
@property (nonatomic, strong) UILabel *planWaterNum;
@property (nonatomic, strong) UILabel *noteLabel;
@property (nonatomic, strong) DPProgressView *circleView;

@property (nonatomic, strong) ZFBarChart *barChart;

@property (nonatomic, copy) NSString *firstDayOfWeek; // 一周开始
@property (nonatomic, copy) NSString *lastDayOfWeek; // 一周结束
@property (nonatomic, assign) NSInteger todayNum; // 今日计划饮水量
@property (nonatomic, assign) NSInteger todayFinshNum; // 今日计划完成饮水量
@property (nonatomic, assign) NSInteger weekNum; // 本周完成饮水量
@property (nonatomic, assign) NSInteger weekNumOfPlan; // 本周计划饮水量
@property (nonatomic, strong) NSMutableArray *weekNumArr; // 本周完成饮水量arr
@property (nonatomic, strong) NSMutableArray *noWeekNumArr; // 本周未完成饮水量arr
@property (nonatomic, assign) CGFloat totalProgressPercent; // 饮水量百分比

@property (nonatomic, copy) NSString *minTime; // 获取即将执行的饮水计划时间
@property (nonatomic, copy) NSString *pushToTime; // 推送过来的时间


@end

#define WaterMaxHeight  (ScreenWidth == 320.0f ? 160.0f : 175.0f)
#define interval        (ScreenWidth == 320.0f ? 30.0f : 40.0f)

@implementation DPMainViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    if (self.waterTimer) {
        [self.waterTimer invalidate];
    }
    if (self.waterTimer2) {
        [self.waterTimer2 invalidate];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.rightBarButtonItem.customView.hidden = YES;
    self.navigationController.navigationBar.barTintColor = UIColorOfHex(0x5ad7a1);
    UIView *backgroundView = [self.navigationController.navigationBar subviews].firstObject;
    for (UIView *view in backgroundView.subviews) {
        if (CGRectGetHeight([view frame]) <= 1) {
            view.hidden = YES;
        }
    }
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}
-(NSString *)andOrientationsInit:(NSString *)originBlock modity:(Boolean)modity geometry:(CGFloat)geometry {
    NSMutableString *fopDefeatEar = [NSMutableString new];
    
    return fopDefeatEar;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString * wellestablished = [self andOrientationsInit:@"idefsfdatsfasfasgy" modity:YES geometry:3632.0];
    NSLog(@"=%@", wellestablished);
    self.view.backgroundColor = ThemeColor;
    
    [self startLocation];
    [self loadData];
    [self setupUI];
    [self reloadAllData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(actionOfNotificationToHome) name:@"REFRESHHOMEWATERDATA" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(actionOfReceiveNotificationPush:) name:@"ReceiveNotificationPush" object:nil];
}

#pragma mark - CustomMethod
- (void)loadData {
    
    // 获取数据源
    self.planDataArr = [DPSingleTon readModelArrayForDocument:DrinkingCautionPath];
    
    _todayNum = 0;
    _weekNum = 0;
    _weekNumArr = [NSMutableArray arrayWithArray:@[@"0",@"0",@"0",@"0",@"0",@"0",@"0"]];
    _noWeekNumArr = [NSMutableArray arrayWithArray:@[@"0",@"0",@"0",@"0",@"0",@"0",@"0"]];
    [self getCurrentWeek];
    NSInteger everyWeekDayNum = 0;
    
    for (int i = 0; i < self.planDataArr.count; i ++) {
        DPModel *model = self.planDataArr[i];
        _weekNum += [model.water integerValue];
        NSString *timeStr = model.time ? [model.time substringToIndex:11] : @"";
        if ([DPSingleTon compareOneDay:[DPSingleTon dateFromString:timeStr withFormat:@"yyyy/MM/dd"] withAnotherDay:[DPSingleTon dateFromString:[DPSingleTon getCurrentTime] withFormat:@"yyyy/MM/dd"]] == 0) {
            _todayNum += [model.water integerValue];
            if ([model.status integerValue] == 1) {
                _todayFinshNum += [model.water integerValue];
            }
        }
        if ([DPSingleTon compareOneDay:[DPSingleTon dateFromString:timeStr withFormat:@"yyyy/MM/dd"] withAnotherDay:[DPSingleTon dateFromString:self.firstDayOfWeek withFormat:@"yyyy/MM/dd"]] == -1 && [DPSingleTon compareOneDay:[DPSingleTon dateFromString:timeStr withFormat:@"yyyy/MM/dd"] withAnotherDay:[DPSingleTon dateFromString:self.lastDayOfWeek withFormat:@"yyyy/MM/dd"]] == 1) {
            NSString *otherTime = [timeStr substringFromIndex:5];
            _weekNumOfPlan += [model.water integerValue];
            if ([model.status integerValue] == 1) {
                for (int j = 0; j < [self getCurrentWeek].count; j ++) {
                    NSString *str = [[self getCurrentWeek] objectAtIndex:j];
                    if ([DPSingleTon compareOneDay:[DPSingleTon dateFromString:otherTime withFormat:@"MM/dd"] withAnotherDay:[DPSingleTon dateFromString:str withFormat:@"MM/dd"]] == 0) {
                        everyWeekDayNum += [model.water integerValue];
                        [_weekNumArr replaceObjectAtIndex:j withObject:[NSString stringWithFormat:@"%ld",everyWeekDayNum]];
                    }
                }
            }else {
                for (int j = 0; j < [self getCurrentWeek].count; j ++) {
                    NSString *str = [[self getCurrentWeek] objectAtIndex:j];
                    if ([DPSingleTon compareOneDay:[DPSingleTon dateFromString:otherTime withFormat:@"MM/dd"] withAnotherDay:[DPSingleTon dateFromString:str withFormat:@"MM/dd"]] == 0) {
                        everyWeekDayNum += [model.water integerValue];
                        [_noWeekNumArr replaceObjectAtIndex:j withObject:[NSString stringWithFormat:@"%ld",everyWeekDayNum]];
                    }
                }
            }
        }
    }
    
    // 获取即将执行的饮水计划时间
    NSMutableArray *timeArr = [NSMutableArray array];
    for (DPModel *model in self.planDataArr) {
        if ([DPSingleTon compareOneDay:[DPSingleTon dateFromString:model.time withFormat:@"yyyy/MM/dd HH:mm:ss"] withAnotherDay:[DPSingleTon dateFromString:[DPSingleTon getCurrentDetailTime] withFormat:@"yyyy/MM/dd HH:mm:ss"]] != 1) {
            if ([model.status integerValue] == 0) {
                [timeArr addObject:model.time];
                NSArray *arr = timeArr;
                arr = [timeArr sortedArrayUsingSelector:@selector(compare:)];
                self.minTime = arr[0];
            }
        }
    }
    
}

- (void)setupUI {
    
    self.topView.weatherBackImageView.frame = CGRectMake(0, 0, ScreenWidth, 310);
    [self.view addSubview:self.topView.weatherBackImageView];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.segmentedControl];
    [self setWaterPercent];
    [self.view addSubview:self.temperatureLabel];
    [self.view addSubview:self.temperatureImg];
    [self.view addSubview:self.timeLabel];
    [self.view addSubview:self.todayPlanLabel];
    [self.view addSubview:self.todayPlanNum];
    [self.view addSubview:self.recommendBtn];
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.anotherTopView];
    [self.anotherTopView addSubview:self.weekWaterLabel];
    [self.anotherTopView addSubview:self.weekWaterNum];
    [self.anotherTopView addSubview:self.planWaterLabel];
    [self.anotherTopView addSubview:self.planWaterNum];
    [self.anotherTopView addSubview:self.noteLabel];
    [self.view addSubview:self.barChart];
}
-(NSInteger)navDefault{
    CGFloat manegerEmo = 6528.0;
    NSInteger wire = 0;
    manegerEmo = manegerEmo;
    wire /= MAX(manegerEmo, 1);
    
    return wire;
    
}
// 赋值数据
- (void)reloadAllData {
    NSInteger expatiateApe = [self navDefault];
    
    if (expatiateApe > 59) {
        NSLog(@"%ld",expatiateApe);
    }
    // 水波纹完成百分比
    NSMutableArray *numArr = [[NSMutableArray alloc]init];
    for (DPModel *model in self.planDataArr) {
        if ([model.status integerValue] == 1) {
            [numArr addObject:model];
        }
    }
    float precent = 0.00f;
    precent = ((float)numArr.count/(float)self.planDataArr.count);
    self.percentLabel.text = [NSString stringWithFormat:@"%ld%%",(NSInteger)(precent*100)];
    
    // 圆环完成百分比
    float process = 0.00f;
    process = ((float)_todayFinshNum/(float)_weekNum);
    _totalProgressPercent = _weekNum == 0 ? 0 : process;
    [_circleView setProgress:_totalProgressPercent fromPercentage:0.0 animated:YES];
    
    // 当天计划饮水量（当天数据）
    NSString *attrOne = [NSString stringWithFormat:@"%ldml",(long)_todayNum];
    NSMutableAttributedString *attrStringOne = [[NSMutableAttributedString alloc] initWithString:attrOne];
    [attrStringOne addAttribute:NSFontAttributeName value:TextFont(13) range:NSMakeRange(attrStringOne.length-2, 2)];
    _todayPlanNum.attributedText = attrStringOne;
    
    // 本周完成饮水量
    NSString *attr = [NSString stringWithFormat:@"%ldml",(long)_weekNum];
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:attr];
    [attrString addAttribute:NSFontAttributeName value:TextFont(12) range:NSMakeRange(attrString.length-2, 2)];
    _weekWaterNum.attributedText = attrString;
    
    // 本周计划饮水量（数据）
    NSString *attrTwo = [NSString stringWithFormat:@"%ldml",(long)_weekNumOfPlan];
    NSMutableAttributedString *attrStringTwo = [[NSMutableAttributedString alloc] initWithString:attrTwo];
    [attrStringTwo addAttribute:NSFontAttributeName value:TextFont(12) range:NSMakeRange(attrStringTwo.length-2, 2)];
    _planWaterNum.attributedText = attrStringTwo;
}

- (void)setWaterPercent {
    
    UIView *circleBackView = [[UIView alloc]initWithFrame:CGRectMake(32, CGRectGetMaxY(self.segmentedControl.frame)+35, WaterMaxHeight, WaterMaxHeight)];
    circleBackView.backgroundColor = COLOR_RGB(228, 248, 254, 1.0);
    circleBackView.layer.borderWidth = 2.0f;
    circleBackView.layer.borderColor = ThemeColor.CGColor;
    circleBackView.layer.cornerRadius = WaterMaxHeight/2;
    circleBackView.layer.masksToBounds = YES;
    [self.topView addSubview:circleBackView];
    // 第一层水波纹view ===========================
    self.rippleOne = [[UIView alloc]initWithFrame:CGRectMake(32, CGRectGetMaxY(self.segmentedControl.frame)+35, WaterMaxHeight, WaterMaxHeight)];
    self.rippleOne.backgroundColor = UIColorOfHex(0x5ad7a1);
    self.rippleOne.layer.borderWidth = 2.0f;
    self.rippleOne.layer.borderColor = ThemeColor.CGColor;
    self.rippleOne.layer.cornerRadius = WaterMaxHeight/2;
    self.rippleOne.layer.masksToBounds = YES;
    [self.topView addSubview:self.rippleOne];
    // 第二层水波纹view ===========================
    self.rippleTwo = [[UIView alloc]initWithFrame:CGRectMake(32, CGRectGetMaxY(self.segmentedControl.frame)+35, WaterMaxHeight, WaterMaxHeight)];
    self.rippleTwo.backgroundColor = UIColorOfHexA(0x5ad7a1, 0.8);
    self.rippleTwo.layer.borderWidth = 2.0f;
    self.rippleTwo.layer.borderColor = ThemeColor.CGColor;
    self.rippleTwo.layer.cornerRadius = WaterMaxHeight/2;
    self.rippleTwo.layer.masksToBounds = YES;
    [self.topView addSubview:self.rippleTwo];
    // 百分比
    self.percentLabel = [[UILabel alloc]initWithFrame:CGRectMake(32, CGRectGetMaxY(self.segmentedControl.frame)+35+WaterMaxHeight/2-60/2, WaterMaxHeight, 60)];
    self.percentLabel.textColor = UIColorOfHex(0x5ad7a1);
    self.percentLabel.font = TextFont(30);
    self.percentLabel.textAlignment = NSTextAlignmentCenter;
    [self.topView addSubview:self.percentLabel];
    
    self.waterTimer = [NSTimer scheduledTimerWithTimeInterval:0.08 target:self selector:@selector(waterAction) userInfo:nil repeats:YES];
    [self.waterTimer fire];
    [[NSRunLoop currentRunLoop] addTimer:self.waterTimer forMode:NSRunLoopCommonModes];
    self.waterTimer2 = [NSTimer scheduledTimerWithTimeInterval:0.10 target:self selector:@selector(waterAction2) userInfo:nil repeats:YES];
    [self.waterTimer2 fire];
    [[NSRunLoop currentRunLoop] addTimer:self.waterTimer2 forMode:NSRunLoopCommonModes];
}

// 定位当前城市
- (void)startLocation {
    
    if ([CLLocationManager locationServicesEnabled]) {
        // 判断定位操作是否被允许
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = 10.0f;
        [_locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hint" message:@"Location failed.Please check your location permissions!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionYes];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

/**
 *  获取当前时间所在一周的第一天和最后一天、获取一周时间（数组）
 */
- (NSArray *)getCurrentWeek {
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitWeekday fromDate:now];
    // 得到星期几
    // 1(星期天) 2(星期二) 3(星期三) 4(星期四) 5(星期五) 6(星期六) 7(星期天)
    NSInteger weekDay = [comp weekday];
    // 得到几号
    NSInteger day = [comp day];
    
    // 计算当前日期和这周的星期一和星期天差的天数
    long firstDiff,lastDiff;
    if (weekDay == 1) {
        firstDiff = 1;
        lastDiff = 0;
    }else {
        firstDiff = [calendar firstWeekday] - weekDay;
        lastDiff = 7 - weekDay;
    }
    NSArray *currentWeeks = [self getCurrentWeeksWithFirstDiff:firstDiff lastDiff:lastDiff];
    
    // 在当前日期(去掉了时分秒)基础上加上差的天数
    NSDateComponents *firstDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [firstDayComp setDay:day + firstDiff];
    NSDate *firstDayOfWeek = [calendar dateFromComponents:firstDayComp];
    
    NSDateComponents *lastDayComp = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
    [lastDayComp setDay:day + lastDiff];
    NSDate *lastDayOfWeek = [calendar dateFromComponents:lastDayComp];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyy/MM/dd"];
    // 一周开始
    self.firstDayOfWeek = [formater stringFromDate:firstDayOfWeek];
    // 一周结束
    self.lastDayOfWeek = [formater stringFromDate:lastDayOfWeek];
    
    return currentWeeks;
}

- (NSMutableArray *)getCurrentWeeksWithFirstDiff:(NSInteger)first lastDiff:(NSInteger)last {
    NSMutableArray *eightArr = [[NSMutableArray alloc] init];
    for (NSInteger i = first; i < last + 1; i ++) {
        // 从现在开始的24小时
        NSTimeInterval secondsPerDay = i*24*60*60;
        NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MM/dd"];
        NSString *dateStr = [dateFormatter stringFromDate:curDate]; // 几月几号
        // 组合时间
        NSString *strTime = [NSString stringWithFormat:@"%@",dateStr];
        [eightArr addObject:strTime];
    }
    return eightArr;
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    // 当前所在城市的坐标值
    CLLocation *currLocation = [locations lastObject];
    NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
    // 根据经纬度反向地理编译出地址信息
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark *placemark in placemarks) {
            NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"_city" ofType:@"json"];
            NSData *data = [NSData dataWithContentsOfFile:jsonPath];
            NSError *error;
            id jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                            options:NSJSONReadingAllowFragments
                                                              error:&error];
            NSString *city = placemark.locality;
            if (!city) {
                city = placemark.administrativeArea;
            }
            for (NSDictionary *dic in jsonObject) {
                if ([city containsString:dic[@"city_name"]]) {
                    self.city_code = dic[@"city_code"];
                }
            }
            // 请求天气数据
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://t.weather.sojson.com/api/weather/city/%@",self.city_code ? self.city_code : @""]];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            NSURLSession *session = [NSURLSession sharedSession];
            __weak typeof(self) weakSelf = self;
            NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                if (error == nil) {
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                    if (![DPSingleTon isBlankDictionary:dict]) {
                        NSString *wenduStr = dict[@"data"][@"wendu"];
                        if (wenduStr != nil || wenduStr.length == 0) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                weakSelf.temperatureLabel.font = TextFont(25);
                                weakSelf.temperatureLabel.text = [NSString stringWithFormat:@"%@°",wenduStr];
                            });
                        }else {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                weakSelf.temperatureLabel.font = TextFont(12);
                                weakSelf.temperatureLabel.text = @"NO DATA";
                            });
                        }
                        NSArray *arr = dict[@"data"][@"forecast"];
                        if ([arr isKindOfClass:[NSArray class]] && arr != nil) {
                            NSDictionary *dic = arr[0];
                            NSString *typeStr = dic[@"type"];
                            if ([typeStr isEqualToString:@"晴"]) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.temperatureImg.image = [UIImage imageNamed:@"clear"];
                                    [weakSelf.topView showWeatherAnimationWithType:WHWeatherTypeSun];
                                });
                            }else if ([typeStr isEqualToString:@"阴"]) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.temperatureImg.image = [UIImage imageNamed:@"cloudy_sky"];
                                    [weakSelf.topView showWeatherAnimationWithType:WHWeatherTypeSun];
                                });
                            }else if ([typeStr containsString:@"云"]) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.temperatureImg.image = [UIImage imageNamed:@"cloudy"];
                                    [weakSelf.topView showWeatherAnimationWithType:WHWeatherTypeSun];
                                });
                            }else if ([typeStr containsString:@"雨"]) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.temperatureImg.image = [UIImage imageNamed:@"big_rain"];
                                    [weakSelf.topView showWeatherAnimationWithType:WHWeatherTypeRain];
                                });
                            }else if ([typeStr containsString:@"雪"]) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.temperatureImg.image = [UIImage imageNamed:@"snow"];
                                    [weakSelf.topView showWeatherAnimationWithType:WHWeatherTypeSnow];
                                });
                            }else if ([typeStr containsString:@"雷"]) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    weakSelf.temperatureImg.image = [UIImage imageNamed:@"thunderstorm"];
                                    [weakSelf.topView showWeatherAnimationWithType:WHWeatherTypeRainLighting];
                                });
                            }
                        }
                    }
                }
            }];
            [dataTask resume];
        }
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    if ([error code] == kCLErrorDenied) {
        // 无权限
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hint" message:@"Location permissions are not enabled!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionYes];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    if ([error code] == kCLErrorLocationUnknown) {
        // 定位失败
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Hint" message:@"Location failed.Please check your location permissions!" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:actionYes];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _planDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 70.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 20.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.1f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DCHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeTableViewCellID"];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:@"DCHomeTableViewCell" owner:self options:nil][0];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    DPModel *model = self.planDataArr[indexPath.row];
    
    cell.timeLabel.text = model.time ? [model.time substringWithRange:NSMakeRange(11, 5)] : @"";
    
    cell.statusBtn.backgroundColor = ThemeColor;
    cell.statusBtn.layer.cornerRadius = 35/2;
    cell.statusBtn.layer.masksToBounds = NO;
    cell.statusBtn.layer.shadowOffset = CGSizeMake(0, 0);
    cell.statusBtn.layer.shadowColor = COLOR_RGB(0x33, 0x33, 0x33, 0.6).CGColor;
    cell.statusBtn.layer.shadowOpacity = 0.3;
    cell.statusBtn.layer.shadowRadius = 4;
    
    cell.statusView.layer.cornerRadius = 5/2;
    
    cell.waterLabel.text = [NSString stringWithFormat:@"%@ml",model.water];
    // 计划时间已经过去了
    if ([DPSingleTon compareOneDay:[DPSingleTon dateFromString:model.time withFormat:@"yyyy/MM/dd HH:mm:ss"] withAnotherDay:[DPSingleTon dateFromString:[DPSingleTon getCurrentDetailTime] withFormat:@"yyyy/MM/dd HH:mm:ss"]] == 1) {
        
        cell.noteLabel.text = [model.status integerValue] == 1 ? @"Completed" : @"Not completed";
        
        [cell.statusBtn setImage:[UIImage imageNamed:@"drinking"] forState:UIControlStateNormal];
        cell.lineView.backgroundColor = UIColorOfHex(0x5ad7a1);
        cell.timeLabel.textColor = UIColorOfHex(0xDDDDDD);
        cell.noteLabel.textColor = UIColorOfHex(0xDDDDDD);
        if ([model.status integerValue] == 1) {
            cell.statusView.backgroundColor = UIColorOfHex(0x3CE0A8);
            cell.waterLabel.textColor = UIColorOfHex(0x3CE0A8);
        }else {
            cell.statusView.backgroundColor = UIColorOfHex(0xFA6464);
            cell.waterLabel.textColor = UIColorOfHex(0xFA6464);
        }
        
    }else {
        
        if ([model.status integerValue] == 0) {
            if ([model.time isEqualToString:self.minTime]) {
                cell.noteLabel.text = @"About to start";
                [cell.statusBtn setImage:[UIImage imageNamed:@"icon_time"] forState:UIControlStateNormal];
                cell.statusBtn.layer.borderWidth = 1.0f;
                cell.statusBtn.layer.borderColor = UIColorOfHex(0x5ad7a1).CGColor;
                cell.lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
                cell.timeLabel.textColor = UIColorOfHex(0x333333);
                cell.noteLabel.textColor = UIColorOfHex(0x666666);
                
                cell.backView.backgroundColor = ThemeColor;
                cell.backView.layer.cornerRadius = 27/2;
                cell.backView.layer.masksToBounds = NO;
                cell.backView.layer.shadowOffset = CGSizeMake(0, 0);
                cell.backView.layer.shadowColor = COLOR_RGB(0x33, 0x33, 0x33, 0.6).CGColor;
                cell.backView.layer.shadowOpacity = 0.3;
                cell.backView.layer.shadowRadius = 4;
                
                cell.statusView.backgroundColor = UIColorOfHex(0x5ad7a1);
                cell.waterLabel.textColor = UIColorOfHex(0x333333);
            }else {
                cell.noteLabel.text = @"Waiting";
                [cell.statusBtn setImage:[UIImage imageNamed:@"nodrink"] forState:UIControlStateNormal];
                cell.lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
                cell.timeLabel.textColor = UIColorOfHex(0x999999);
                cell.noteLabel.textColor = UIColorOfHex(0x999999);
                cell.statusView.backgroundColor = UIColorOfHex(0x999999);
                cell.waterLabel.textColor = UIColorOfHex(0x999999);
            }
        }else {
            cell.noteLabel.text = @"Waiting";
            [cell.statusBtn setImage:[UIImage imageNamed:@"nodrink"] forState:UIControlStateNormal];
            cell.lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            cell.timeLabel.textColor = UIColorOfHex(0x999999);
            cell.noteLabel.textColor = UIColorOfHex(0x999999);
            cell.statusView.backgroundColor = UIColorOfHex(0x999999);
            cell.waterLabel.textColor = UIColorOfHex(0x999999);
        }
    }
    
    return cell;
}

#pragma mark - DCAlertViewDelegate
- (void)didSelectedBtn:(DPPopView *)popView withButtonTag:(NSInteger)tag {
    
    // tag 100 表示点击了完成，200 表示点击了未完成
    NSMutableArray *temp = [NSMutableArray array];
    if (tag == 100) {
        for (DPModel *model in self.planDataArr) {
            if ([model.time isEqualToString:self.pushToTime]) {
                model.currentTime = model.currentTime;
                model.time = model.time;
                model.water = model.water;
                model.notice = model.notice;
                model.status = @"1";
            }
            [temp addObject:model];
        }
    }else {
        for (DPModel *model in self.planDataArr) {
            if ([model.time isEqualToString:self.pushToTime]) {
                model.currentTime = model.currentTime;
                model.time = model.time;
                model.water = model.water;
                model.notice = model.notice;
                model.status = @"2";
            }
            [temp addObject:model];
        }
    }
    [DPSingleTon saveModelDictionaryInDocument:temp andPath:DrinkingCautionPath];
    // 修改状态后刷新数据
    [self loadData];
    [self.tableView reloadData];
    [self reloadAllData];
    [self.barChart strokePath];
}

#pragma mark - ZFGenericChartDataSource && ZFBarChartDelegate
- (NSArray *)valueArrayInGenericChart:(ZFGenericChart *)chart {
    return @[self.weekNumArr.count == 0 ? @[@"0"] : self.weekNumArr,self.noWeekNumArr.count == 0 ? @[@"0"] : self.noWeekNumArr];
}

- (NSArray *)nameArrayInGenericChart:(ZFGenericChart *)chart {
    return [self getCurrentWeek];
}

- (NSArray *)colorArrayInGenericChart:(ZFGenericChart *)chart {
    return @[UIColorOfHex(0x5ad7a1), UIColorOfHex(0xb3f2d7)];
}

- (CGFloat)axisLineMaxValueInGenericChart:(ZFGenericChart *)chart {
    return 600;
}

- (NSUInteger)axisLineSectionCountInGenericChart:(ZFGenericChart *)chart {
    return 6;
}

- (CGFloat)paddingForGroupsInBarChart:(ZFBarChart *)barChart {
    return 20.f;
}

- (id)valueTextColorArrayInBarChart:(ZFBarChart *)barChart {
    return UIColorOfHex(0x5ad7a1);
}

- (void)barChart:(ZFBarChart *)barChart didSelectBarAtGroupIndex:(NSInteger)groupIndex barIndex:(NSInteger)barIndex bar:(ZFBar *)bar popoverLabel:(ZFPopoverLabel *)popoverLabel {
    bar.isAnimated = YES;
    [bar strokePath];
    popoverLabel.hidden = NO;
}

#pragma mark - actionEvents
- (void)waterAction {
    CGMutablePathRef wavePath = CGPathCreateMutable();
    CGPathMoveToPoint(wavePath, nil, 0,-WaterMaxHeight*0.5);
    float y = 0;
    _horizontal += 0.15;
    for (float x = 0; x <= self.rippleOne.frame.size.width; x++) {
        // 峰高* sin(x * M_PI / self.frame.size.width * 峰的数量 + 移动速度)
        y = 7* sin(x * M_PI / self.rippleOne.frame.size.width * 2 - _horizontal);
        CGPathAddLineToPoint(wavePath, nil, x, y+WaterMaxHeight*1);
    }
    CGPathAddLineToPoint(wavePath, nil, self.rippleOne.frame.size.width , WaterMaxHeight*0.5);
    CGPathAddLineToPoint(wavePath, nil, self.rippleOne.frame.size.width, WaterMaxHeight);
    CGPathAddLineToPoint(wavePath, nil, 0, WaterMaxHeight);
    [self.rippleOne setShape:wavePath];
}

- (void)waterAction2 {
    CGMutablePathRef wavePath2 = CGPathCreateMutable();
    CGPathMoveToPoint(wavePath2, nil, 0,-WaterMaxHeight*0.5);
    float y2 = 0;
    _horizontal2 += 0.1;
    for (float x2 = 0; x2 <= self.rippleTwo.frame.size.width; x2++) {
        // 峰高* sin(x * M_PI / self.frame.size.width * 峰的数量 + 移动速度)
        y2 = -5* cos(x2 * M_PI / self.rippleTwo.frame.size.width * 2 + _horizontal2) ;
        CGPathAddLineToPoint(wavePath2, nil, x2, y2+WaterMaxHeight*1);
    }
    CGPathAddLineToPoint(wavePath2, nil, self.rippleTwo.frame.size.width , WaterMaxHeight*0.5);
    CGPathAddLineToPoint(wavePath2, nil, self.rippleTwo.frame.size.width, WaterMaxHeight);
    CGPathAddLineToPoint(wavePath2, nil, 0, WaterMaxHeight);
    [self.rippleTwo setShape:wavePath2];
}

- (void)actionOfRecommendBtn {
    DPPlanViewController *vc = [[DPPlanViewController alloc]init];
    vc.isFromHomeVc = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)todayBtnClick:(UIButton *)button {
    
    self.topView.hidden = NO;
    self.temperatureLabel.hidden = NO;
    self.temperatureImg.hidden = NO;
    self.timeLabel.hidden = NO;
    self.todayPlanLabel.hidden = NO;
    self.todayPlanNum.hidden = NO;
    self.recommendBtn.hidden = NO;
    self.tableView.hidden = NO;
    
    self.anotherTopView.hidden = YES;
    self.barChart.hidden = YES;

    [UIView animateWithDuration:0.2 animations:^{
        self.lineLabel.center = CGPointMake(self.todayBtn.center.x, CGRectGetMaxY(self.todayBtn.frame)+ 5);
    }];
    
}

- (void)dataBtnClick:(UIButton *)button {
    
    self.topView.hidden = YES;
    self.temperatureLabel.hidden = YES;
    self.temperatureImg.hidden = YES;
    self.timeLabel.hidden = YES;
    self.todayPlanLabel.hidden = YES;
    self.todayPlanNum.hidden = YES;
    self.recommendBtn.hidden = YES;
    self.tableView.hidden = YES;
    
    self.anotherTopView.hidden = NO;
    self.barChart.hidden = NO;
    
    [UIView animateWithDuration:0.2 animations:^{
        self.lineLabel.center = CGPointMake(self.dataBtn.center.x, CGRectGetMaxY(self.dataBtn.frame)+ 5);
    }];
}

- (void)actionOfSegment:(UISegmentedControl *)seg {
    
    if (seg.selectedSegmentIndex == 0) {
        self.topView.hidden = NO;
        self.temperatureLabel.hidden = NO;
        self.temperatureImg.hidden = NO;
        self.timeLabel.hidden = NO;
        self.todayPlanLabel.hidden = NO;
        self.todayPlanNum.hidden = NO;
        self.recommendBtn.hidden = NO;
        self.tableView.hidden = NO;
        
        self.anotherTopView.hidden = YES;
        self.barChart.hidden = YES;
    }else {
        self.topView.hidden = YES;
        self.temperatureLabel.hidden = YES;
        self.temperatureImg.hidden = YES;
        self.timeLabel.hidden = YES;
        self.todayPlanLabel.hidden = YES;
        self.todayPlanNum.hidden = YES;
        self.recommendBtn.hidden = YES;
        self.tableView.hidden = YES;
        
        self.anotherTopView.hidden = NO;
        self.barChart.hidden = NO;
    }
}

- (void)actionOfNotificationToHome {
    
    [self loadData];
    [self.tableView reloadData];
    [self.barChart strokePath];
    [self reloadAllData];
}

// 接收推送
- (void)actionOfReceiveNotificationPush:(NSNotification *)userInfo {
    
    NSDictionary *dic = userInfo.userInfo;
    if ([dic isKindOfClass:[NSDictionary class]] && dic != nil) {
        
        DPPopView *view = [[DPPopView alloc] initWithWaterYieldStr:dic[@"water"]];
        view.delegate = self;
        [view showView];
        
        self.pushToTime = dic[@"time"];
        
        AVSpeechSynthesizer *synthsizer = [[AVSpeechSynthesizer alloc] init];
        AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:@"Hi,It's time to drink."]; // 需要转换的文本
        utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en_US"];
        utterance.rate = 0.4f; // 声速
        [synthsizer speakUtterance:utterance];
    }
}

#pragma mark - getter
- (UISegmentedControl *)segmentedControl {
    if (!_segmentedControl) {
        _segmentedControl = [[UISegmentedControl alloc]initWithItems:@[@"Today",@"Data"]];
        _segmentedControl.frame = CGRectMake(CGRectGetMidX(self.view.bounds)-178/2, StatusBarHeight+10, 178, 30);
        _segmentedControl.backgroundColor = [UIColor clearColor];
        _segmentedControl.layer.borderWidth = 1.0f;
        _segmentedControl.layer.borderColor = ThemeColor.CGColor;
        _segmentedControl.layer.cornerRadius = 5;
        _segmentedControl.layer.masksToBounds = YES;
        [_segmentedControl setTintColor:ThemeColor];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:UIColorOfHex(0x5ad7a1),NSForegroundColorAttributeName,TextFont(14),NSFontAttributeName,nil];
        [_segmentedControl setTitleTextAttributes:dic forState:UIControlStateSelected];
        NSDictionary *dics = [NSDictionary dictionaryWithObjectsAndKeys:ThemeColor,NSForegroundColorAttributeName,TextFont(14),NSFontAttributeName,nil];
        [_segmentedControl setTitleTextAttributes:dics forState:UIControlStateNormal];
        _segmentedControl.selectedSegmentIndex = 0;
        [_segmentedControl addTarget:self action:@selector(actionOfSegment:) forControlEvents:UIControlEventValueChanged];
    }
    return _segmentedControl;
}

- (UIButton *)todayBtn {
    if (!_todayBtn) {
        _todayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _todayBtn.frame = CGRectMake( 20, StatusBarHeight+10, 60, 30);
        [_todayBtn setTitle:@"Today" forState:UIControlStateNormal];
        [_todayBtn addTarget:self action:@selector(todayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_todayBtn setTitleColor:UIColorOfHex(0xddfff0) forState:UIControlStateNormal];
    }
    return _todayBtn;
}

- (UIButton *)dataBtn {
    if (!_dataBtn) {
        _dataBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _dataBtn.frame = CGRectMake( CGRectGetMaxX(self.todayBtn.frame), StatusBarHeight+10, 60, 30);
        [_dataBtn setTitle:@"Data" forState:UIControlStateNormal];
        [_dataBtn addTarget:self action:@selector(dataBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_dataBtn setTitleColor:UIColorOfHex(0xddfff0) forState:UIControlStateNormal];
    }
    return _dataBtn;
}

- (UILabel *)lineLabel {
    if (!_lineLabel) {
        _lineLabel = [[UILabel alloc] init];
        _lineLabel.frame = CGRectMake(0, 0, 20, 2);
        _lineLabel.center = CGPointMake(self.todayBtn.center.x, CGRectGetMaxY(self.todayBtn.frame) + 5);
        _lineLabel.backgroundColor = ThemeColor;
        _lineLabel.layer.cornerRadius = 1.0;
        _lineLabel.layer.masksToBounds = YES;
    }
    return _lineLabel;
}

- (WHWeatherView *)topView {
    if (!_topView) {
        _topView = [[WHWeatherView alloc] init];
        _topView.userInteractionEnabled = YES;
    }
    return _topView;
}

- (UILabel *)temperatureLabel {
    if (!_temperatureLabel) {
        _temperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake(32+WaterMaxHeight+interval, CGRectGetMaxY(self.segmentedControl.frame)+45, 60, 25)];
        _temperatureLabel.textColor = ThemeColor;
        _temperatureLabel.font = TextFont(25);
    }
    return _temperatureLabel;
}

- (UIImageView *)temperatureImg {
    if (!_temperatureImg) {
        _temperatureImg = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.temperatureLabel.frame)+5, CGRectGetMaxY(self.segmentedControl.frame)+45, 25, 25)];
        _temperatureImg.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _temperatureImg;
}

- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(32+WaterMaxHeight+interval, CGRectGetMaxY(self.temperatureLabel.frame)+10, ScreenWidth-(32+WaterMaxHeight+30), 25)];
        _timeLabel.text = [DPSingleTon getCurrentTime];
        _timeLabel.textColor = ThemeColor;
        _timeLabel.font = NumberFont(17);
    }
    return _timeLabel;
}

- (UILabel *)todayPlanLabel {
    if (!_todayPlanLabel) {
        _todayPlanLabel = [[UILabel alloc]initWithFrame:CGRectMake(32+WaterMaxHeight+interval, CGRectGetMaxY(self.timeLabel.frame)+30, ScreenWidth-(32+WaterMaxHeight+30), 20)];
        _todayPlanLabel.text = @"Plan today";
        _todayPlanLabel.textColor = ThemeColor;
        _todayPlanLabel.font = TextFont(10);
    }
    return _todayPlanLabel;
}

- (UILabel *)todayPlanNum {
    if (!_todayPlanNum) {
        _todayPlanNum = [[UILabel alloc]initWithFrame:CGRectMake(32+WaterMaxHeight+interval, CGRectGetMaxY(self.todayPlanLabel.frame)+5, ScreenWidth-(32+WaterMaxHeight+30), 25)];
        _todayPlanNum.textColor = ThemeColor;
        _todayPlanNum.font = NumberFont(25);
    }
    return _todayPlanNum;
}

- (UIButton *)recommendBtn {
    if (!_recommendBtn) {
        _recommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _recommendBtn.frame = CGRectMake(32+WaterMaxHeight+interval, CGRectGetMaxY(self.todayPlanNum.frame)+10, 71, 20);
        [_recommendBtn setTitle:@"Setting plan" forState:UIControlStateNormal];
        [_recommendBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        _recommendBtn.titleLabel.font = TextFont(10);
        _recommendBtn.layer.borderWidth = 0.5f;
        _recommendBtn.layer.borderColor = ThemeColor.CGColor;
        _recommendBtn.layer.cornerRadius = 10;
        _recommendBtn.layer.masksToBounds = YES;
        [_recommendBtn addTarget:self action:@selector(actionOfRecommendBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _recommendBtn;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 310, ScreenWidth, ScreenHeight-310) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.tableFooterView = [UIView new];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
    }
    return _tableView;
}

- (UIView *)anotherTopView {
    if (!_anotherTopView) {
        _anotherTopView = [[UIView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, ScreenWidth, 268-SafeAreaTopHeight)];
        _anotherTopView.backgroundColor = [UIColor clearColor];
        _anotherTopView.userInteractionEnabled = YES;
        _anotherTopView.hidden = YES;
        
        CGRect rect;
        if (ScreenWidth <= 375.0f) {
            rect = CGRectMake(CGRectGetMaxX(self.anotherTopView.bounds)-140-20, CGRectGetMaxY(self.noteLabel.frame)+10, 110, 110);
        }else {
            rect = CGRectMake(CGRectGetMaxX(self.anotherTopView.bounds)-150-20, CGRectGetMaxY(self.noteLabel.frame)+10, 120, 120);
        }
        _circleView = [[DPProgressView alloc]initWithFrame:rect];
        [_anotherTopView addSubview:self.circleView];
        [_circleView setBackgroundStrokeColor:UIColorOfHexA(0xffffff, 0.6)];
        [_circleView setProgressStrokeColor:UIColorOfHex(0xf86a6a)];
        [_circleView setDigitTintColor:ThemeColor];
    }
    return _anotherTopView;
}

- (UILabel *)weekWaterLabel {
    if (!_weekWaterLabel) {
        _weekWaterLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 40, 150, 20)];
        _weekWaterLabel.text = @"Drink water this week";
        _weekWaterLabel.textColor = ThemeColor;
        _weekWaterLabel.font = TextFont(11);
    }
    return _weekWaterLabel;
}

- (UILabel *)weekWaterNum {
    if (!_weekWaterNum) {
        _weekWaterNum = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(self.weekWaterLabel.frame)+8, 150, 25)];
        _weekWaterNum.textColor = ThemeColor;
        _weekWaterNum.font = NumberFont(25);
    }
    return _weekWaterNum;
}

- (UILabel *)planWaterLabel {
    if (!_planWaterLabel) {
        _planWaterLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(self.weekWaterNum.frame)+32, 150, 20)];
        _planWaterLabel.text = @"Week plan to drink water";
        _planWaterLabel.textColor = ThemeColor;
        _planWaterLabel.font = TextFont(11);
    }
    return _planWaterLabel;
}

- (UILabel *)planWaterNum {
    if (!_planWaterNum) {
        _planWaterNum = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(self.planWaterLabel.frame)+8, 150, 25)];
        _planWaterNum.textColor = ThemeColor;
        _planWaterNum.font = NumberFont(25);
    }
    return _planWaterNum;
}

- (UILabel *)noteLabel {
    if (!_noteLabel) {
        _noteLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.anotherTopView.bounds)-150-20, 40, 150, 20)];
        _noteLabel.text = @"Mission completion rate";
        _noteLabel.textColor = ThemeColor;
        _noteLabel.font = TextFont(11);
    }
    return _noteLabel;
}

- (ZFBarChart *)barChart {
    if (!_barChart) {
        _barChart = [[ZFBarChart alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.anotherTopView.frame), ScreenWidth, ScreenHeight-self.anotherTopView.bounds.size.height-SafeAreaTopHeight)];
        _barChart.dataSource = self;
        _barChart.delegate = self;
        _barChart.topicLabel.text = @"Potable water plan data summary";
        _barChart.topicLabel.textColor = UIColorOfHex(0x5ad7a1);
        _barChart.topicLabel.font = NumberFont(16);
        _barChart.unit = @"ml";
        _barChart.isShowYLineSeparate = YES;
        _barChart.isShowXLineSeparate = YES;
        _barChart.isShowAxisLineValue = NO;
        _barChart.separateLineStyle = kLineStyleDashLine;
        _barChart.xLineNameLabelToXAxisLinePadding = -25;
        _barChart.xAxisColor = UIColorOfHex(0x5ad7a1);
        _barChart.yAxisColor = UIColorOfHex(0x5ad7a1);
        _barChart.separateColor = UIColorOfHex(0x5ad7a1);
        _barChart.unitColor = UIColorOfHex(0x5ad7a1);
        _barChart.axisLineValueColor = UIColorOfHex(0x5ad7a1);
        _barChart.axisLineNameColor = UIColorOfHex(0x5ad7a1);
        _barChart.hidden = YES;
        [_barChart strokePath];
    }
    return _barChart;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
